package dao

import (
	"blog/model"
	"sort"
)

var TopicDao = &topicDao{}

type topicDao struct {
}

// 查询文章
func (dao topicDao) TopicGet(id interface{}) (*model.Topic, bool) {
	mod := &model.Topic{}
	switch val := id.(type) {
	case int:
		has, _ := Db.ID(val).Get(mod)
		return mod, has
	default:
		return mod, false
	}
}

func (dao topicDao) TopicTree() TreeSlice {
	list := &[]model.Topic{}
	_ = Db.Where("data_state = 0").OrderBy("topic_id").Find(list, new(model.Topic))
	topicMap := make(map[int]*TreeDTO)
	for _, value := range *list {
		topicDto := &TreeDTO{Topic: value, Children: []*TreeDTO{}}
		topicMap[value.TopicId] = topicDto
	}
	var result TreeSlice
	for _, value := range topicMap {
		if topicMap[value.ParentId] == nil {
			result = append(result, value)
			continue
		}
		topicMap[value.ParentId].Children = append(topicMap[value.ParentId].Children, value)
	}
	sort.Sort(result)
	return result
}

type TreeDTO struct {
	model.Topic
	Children TreeSlice `json:"children"`
}

type TreeSlice []*TreeDTO

func (tree TreeSlice) Swap(i, j int) {
	tree[i], tree[j] = tree[j], tree[i]
}

func (tree TreeSlice) Len() int {
	return len(tree)
}

func (tree TreeSlice) Less(i, j int) bool {
	return tree[i].TopicId < tree[j].TopicId
}
